from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware

from middlewares.exceptions import UnauthenticatedException
from middlewares.middlewares import LoggingMiddleware, generate_response
from sqlalchemy.orm import sessionmaker

from schemas.models import Base
from routes.routers import v1, v2, v1_admin

# 创建FastAPI应用
app = FastAPI(title="订阅管理系统API", description="用于管理用户订阅的API系统", version="1.0.0")

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000", "http://127.0.0.1:3000"],  # 在生产环境中，应该指定允许的源
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
app.add_middleware(LoggingMiddleware)

from schemas.database import engine

# 添加日志请求中间件
# 数据库配置
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建数据库表
Base.metadata.create_all(bind=engine)
@v1.get("/init_data")
async def init_data():
    from utils.init import init_db
    info = await init_db()
    return {"message": info}
# 添加路由
app.include_router(v1, prefix="/api/v1")
app.include_router(v1_admin, prefix="/api/v1/admin")
app.include_router(v2, prefix="/api/v2")
# 根路由
# app.mount("/", StaticFiles(directory="./templates", html=True))



# 自定义异常处理
from fastapi.exceptions import HTTPException as FastAPIHTTPException, RequestValidationError


@app.exception_handler(FastAPIHTTPException)
async def custom_http_exception_handler(request, exc):
    print(exc.status_code)
    print(exc.detail)
    return generate_response(data=None, status_code=exc.status_code, message=exc.detail)

# 未登录授权错误
@app.exception_handler(UnauthenticatedException)
async def custom_http_exception_handler(request, exc):
    return generate_response(data=None, status_code=401, message="禁止访问")

@app.exception_handler(Exception)
async def custom_exception_handler(request, exc):
    print(exc)
    return generate_response(data=None, status_code=500, message=str(exc))

# 参数校验错误
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return generate_response(data=exc.errors(), status_code=500, message="系统错误: args")

@app.middleware("http")
async def catch_404(request: Request, call_next):
    try:
        response = await call_next(request)
        if response.status_code == 404:
            return generate_response(data=None, status_code=404, message="Error path")
    except Exception as e:
        print(e)
        raise e
    return response